﻿using System;
using System.Collections.Generic;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Data;
using System.IO;
using System.Configuration;

using Museum.DBAccess;

public partial class GameDetails : System.Web.UI.Page
{
    protected void Page_Load(object sender, EventArgs e)
    {
        if (!Page.IsPostBack)
        {
            string strWatermarkSearch = "0.00";
            DataTable dtMuseums = null;
            txtGamePrice.Text = strWatermarkSearch;
            txtGamePrice.Attributes.Add("onfocus", "WatermarkFocus(this, '" + strWatermarkSearch + "');");
            txtGamePrice.Attributes.Add("onblur", "WatermarkBlur(this, '" + strWatermarkSearch + "');");

            dtMuseums = DBAccess.GetMuseumByCity("");

            if (Session["Role"] != null && Session["SchoolId"] != null)
            {
                dtMuseums.Clear();
                if (Session["Role"].ToString().Equals("2"))
                {
                    dtMuseums.Clear();
                    dtMuseums = DBAccess.GetMuseumBySchoolId(Convert.ToInt32(Session["SchoolId"]));
                }
                else
                {
                    dtMuseums.Clear();
                    dtMuseums = DBAccess.GetMuseumBySchoolId(Convert.ToInt32(Session["SchoolId"]));
                }
            }
            if (dtMuseums != null && dtMuseums.Rows.Count > 0)
            {
                ddlMuseum.DataSource = dtMuseums;
                ddlMuseum.DataBind();
            }
            
            if (Session["Role"] != null && Session["SchoolId"] != null)
            {
                if (Session["MuseumId"] != null)
                {
                    if (Convert.ToInt32(Session["MuseumId"]) > 0)
                    {
                        if (Session["IsMuseum"] != null)
                        {
                            ddlMuseum.SelectedValue = Session["MuseumId"].ToString();
                            ddlMuseum.Enabled = false;
                        }
                        else
                        {
                            ddlMuseum.SelectedValue = Session["MuseumId"].ToString();
                            ddlMuseum.Enabled = true;
                        }
                    }
                }
            }
            else if (Session["MuseumId"] != null)
            {
                if (Convert.ToInt32(Session["MuseumId"]) > 0)
                {
                    ddlMuseum.SelectedValue = Session["MuseumId"].ToString();
                    ddlMuseum.Enabled = false;
                }
            }

            if (Request.QueryString["GameID"] != null)
            {
                BindGameData();
                ddlMuseum.Enabled = false;
            }
        }
    }

    protected void btnSubmit_Click(object sender, EventArgs e)
    {
        byte[] thumbnailData = null;
        string thumbnailURL = string.Empty;
        byte[] treasureData = null;
        string treasureURL = string.Empty;
        int gameID = 0;
        int newGameID = 0;
        int museumID = 0;
        try
        {
            if (Request.QueryString["GameID"] != null)
                gameID = Convert.ToInt32(Request.QueryString["GameID"]);

            museumID = Convert.ToInt32(ddlMuseum.SelectedItem.Value);

            #region "File Upload logic"
            if (fileGameImage.HasFile)
            {
                thumbnailData = new byte[fileGameImage.FileBytes.Length];
                thumbnailData = fileGameImage.FileBytes;

                //Create a new subfolder under the current active folder
                string newPath = System.IO.Path.Combine(AppDomain.CurrentDomain.BaseDirectory + @"Games/", txtGameName.Text.Trim());

                // Create the subfolder
                System.IO.Directory.CreateDirectory(newPath);

                // Combine the new file name with the path
                newPath = System.IO.Path.Combine(newPath, fileGameImage.FileName);

                FileStream fs = new FileStream(newPath, FileMode.Create, FileAccess.Write);
                fs.Write(thumbnailData, 0, thumbnailData.Length);
                fs.Close();

                thumbnailURL = ConfigurationManager.AppSettings["ServerURL"] + @"Games/" + txtGameName.Text.Trim() + "/" + fileGameImage.FileName;
            }

            if (fileTreasureImage.HasFile)
            {
                treasureData = new byte[fileTreasureImage.FileBytes.Length];
                treasureData = fileTreasureImage.FileBytes;

                //Create a new subfolder under the current active folder
                string newPath = System.IO.Path.Combine(AppDomain.CurrentDomain.BaseDirectory + @"Treasures/", txtTreasureName.Text.Trim());

                // Create the subfolder
                System.IO.Directory.CreateDirectory(newPath);

                // Combine the new file name with the path
                newPath = System.IO.Path.Combine(newPath, fileTreasureImage.FileName);

                FileStream fs1 = new FileStream(newPath, FileMode.Create, FileAccess.Write);
                fs1.Write(treasureData, 0, treasureData.Length);
                fs1.Close();

                treasureURL = ConfigurationManager.AppSettings["ServerURL"] + @"Treasures/" + txtTreasureName.Text.Trim() + "/" + fileTreasureImage.FileName;
            }
            #endregion

            decimal gamePrice = Convert.ToDecimal(txtGamePrice.Text);

            int totalClues = Convert.ToInt32(txtTotalClues.Text.Trim());

            int isSchoolGame = 0;
            int schoolId = 0;

            if (Session["Role"] != null && Session["SchoolId"] != null)
            {
                if (Session["Role"].ToString().Equals("2") || Session["Role"].ToString().Equals("0"))
                    isSchoolGame = 1;

                schoolId = Convert.ToInt32(Session["SchoolId"]);
            }

            newGameID = DBAccess.InsertOrUpdateGameDetails(gameID, Convert.ToInt32(ddlMuseum.SelectedItem.Value), txtGameName.Text.Trim(), "",
                txtGameAlias.Text.Trim(), txtGameDescription.Text.Trim(), DateTime.Now.AddDays(10), Convert.ToBoolean(ddlIsActive.SelectedItem.Value.Equals("1") ? "true" : "false"),
                Convert.ToInt32(ddlGameLevel.SelectedItem.Value), isSchoolGame,
                Convert.ToInt32(txtGameDuration.Text.Trim()), Convert.ToInt32(txtGameVersion.Text.Trim()), gamePrice, txtAppLink.Text.Trim(),
                thumbnailURL, ddlGameType.SelectedItem.Value, schoolId, txtTreasureName.Text.Trim(), txtTreasureInfo.Text.Trim(), treasureURL, newGameID, totalClues);

            //store game type
            int gameType = Convert.ToInt32(ddlGameType.SelectedValue);

            if (gameID > 0)
            {
                Alert.ShowMessage("Game updated successfully.");
                Response.Redirect("ManageGame.aspx", false);
            }
            else
            {
                Alert.ShowMessage("Game inserted successfully.");
                Response.Redirect("ClueDetails.aspx?PageMode=New&GameType=" + gameType.ToString()
                    + "&GameID=" + gameID.ToString() + "&TotalClues=" + txtTotalClues.Text.Trim() + "&NewGameID=" + newGameID.ToString()
                    + "&MuseumID=" + museumID.ToString(), false);
            }
        }
        catch (Exception ex)
        {
            throw ex;
        }
    }
    protected void btnReset_Click(object sender, EventArgs e)
    {
        txtGameName.Text = "";
        txtGameAlias.Text = "";
        txtGameDescription.Text = "";
        txtGamePrice.Text = "";
        txtGameDuration.Text = "";
        txtGameVersion.Text = "";
        txtTreasureInfo.Text = "";
        txtTreasureName.Text = "";
        ddlGameLevel.SelectedIndex = 0;
        ddlIsActive.SelectedIndex = 0;
        ddlMuseum.SelectedIndex = 0;
    }

    /// <summary>
    /// Binds my grid data.
    /// </summary>
    private void BindGameData()
    {
        DataTable dtGame = new DataTable();
        try
        {
            dtGame = DBAccess.GetGameById(Convert.ToInt32(Request.QueryString["GameID"]));

            if (dtGame != null && dtGame.Rows.Count > 0)
            {
                txtGameName.Text = dtGame.Rows[0]["GameName"].ToString();
                txtGameAlias.Text = dtGame.Rows[0]["GameAlias"].ToString();
                txtGameDescription.Text = dtGame.Rows[0]["GameDescription"].ToString();
                txtGamePrice.Text = dtGame.Rows[0]["GamePrice"].ToString();
                txtGameDuration.Text = dtGame.Rows[0]["GameDuration"].ToString();
                txtGameVersion.Text = dtGame.Rows[0]["GameVersion"].ToString();
                txtAppLink.Text = dtGame.Rows[0]["AppLink"].ToString();
                ddlGameLevel.SelectedValue = dtGame.Rows[0]["GameLevel"].ToString();
                ddlIsActive.SelectedValue = dtGame.Rows[0]["IsActive"].ToString().Equals("True") ? "1" : "0";
                ddlMuseum.SelectedValue = dtGame.Rows[0]["MuseumId"].ToString();
                ddlGameType.SelectedValue = dtGame.Rows[0]["GameType"].ToString();
                txtTreasureName.Text = dtGame.Rows[0]["TreasureName"].ToString();
                txtTreasureImagePath.Text = dtGame.Rows[0]["TreasureImagePath"].ToString();
                txtTreasureImagePath.ToolTip = dtGame.Rows[0]["TreasureImagePath"].ToString();
                txtTreasureInfo.Text = dtGame.Rows[0]["TreasureDetails"].ToString();
                txtTotalClues.Text = dtGame.Rows[0]["NoOfClues"].ToString();
                if (!string.IsNullOrEmpty(dtGame.Rows[0]["GameThumbnailPath"].ToString()))
                    imgGameThumb.Src = "ThumbnailConverter.ashx?location=Games/" + dtGame.Rows[0]["GameName"].ToString() + dtGame.Rows[0]["GameThumbnailPath"].ToString().Substring(dtGame.Rows[0]["GameThumbnailPath"].ToString().LastIndexOf('/'));
            }
        }
        catch
        {
        }
        finally
        {
        }
    }
}